package com.padgett.resourcemanagement.client;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.padgett.resourcemanagement.data.ClientDAO;

/**
 * Get Business Client including all services and invoices.
 * 
 * @author andyleung
 * 
 */
@SuppressWarnings("serial")
public class GetClientServlet extends HttpServlet{
	@SuppressWarnings("unused")
	private static final Logger logger=Logger.getLogger(GetClientServlet.class.getName());
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		String clientKey=req.getParameter("clientId");
		Key key=KeyFactory.stringToKey(clientKey);
		Entity client=ClientDAO.loadEntity(key);
		req.setAttribute("clientId", KeyFactory.keyToString(client.getKey()));
		Iterator<Entry<String, Object>> propertyIterator=client.getProperties().entrySet().iterator();
		while(propertyIterator.hasNext()){
			Map.Entry<String, Object> entry=(Map.Entry<String, Object>)propertyIterator.next();
			String entryKey=entry.getKey();
			if(entry.getValue() instanceof Text){
				req.setAttribute(entryKey, ((Text)entry.getValue()).getValue());
			}else{
				req.setAttribute(entryKey, entry.getValue());
			}
			if(entryKey.equalsIgnoreCase("accountant")&&entry.getValue()!=null){
				// Get Accountant nickname
				Key accountantKey=new KeyFactory.Builder("User",(String)entry.getValue()).getKey();
				Entity accountant=ClientDAO.loadEntity(accountantKey);
				if(accountant!=null){
					req.setAttribute("AccountantName",accountant.getProperty("Nickname"));
				}
			}
		}
		RequestDispatcher dispatcher=req.getRequestDispatcher("/WEB-INF/client.jsp");
		dispatcher.forward(req, resp);
	}
}
